package it.enea.xlab.firstcrud.crudmanager;

import it.enea.xlab.firstcrud.entity.Supplier;

import java.io.Serializable;
import java.util.HashMap;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


/**
 * @author X-Lab
 * 
 * Wrapper remoto di CRUDManagerImpl locale
 */

@Stateless
@Interceptors({Profile.class})
public class CRUDManagerImplJPAFacade implements CRUDManagerRemote, Serializable {
	
	@PersistenceContext(unitName="CRUDPersistenceLayer")
	private EntityManager eM; 
	

	public Long createSupplier(Supplier supplier) {
		
		//eM.persist(supplier.getTranslationType());
		//eM.persist(supplier.getTransmissionType());
		eM.persist(supplier);
		
		//eM.flush();
		
		return supplier.getSupplierId();
	}

	public Supplier readSupplier(Long supplierId) {
	
		return eM.find(Supplier.class, supplierId);
		//return domain.readSupplier(supplierId);
	}

	/**
	 * restituisce false in caso di 
	 * IllegalArgumentException - if instance is not an entity or is a removed entity
	 * 
	 * restituisce null in caso di 
	 * IllegalStateException - if this EntityManager has been closed.
	 * TransactionRequiredException - if invoked on a container-managed entity manager of type PersistenceContextType.TRANSACTION and there is no transaction.
	 */
	public Boolean updateSupplier(Supplier supplier) {
		
		 try {
			eM.merge(supplier);
		} catch (IllegalArgumentException e) {
			return false;
		} catch (Exception e2) {
			return null;
		}
		 
		 return true;
	}

	/**
	 * restituisce false in caso 
	 * la readSupplier torni null
	 * IllegalArgumentException - if instance is not an entity or is a removed entity
	 * 
	 * restituisce null in caso di 
	 * IllegalStateException - if this EntityManager has been closed.
	 * TransactionRequiredException - if invoked on a container-managed entity manager of type PersistenceContextType.TRANSACTION and there is no transaction.
	 */
	public Boolean deleteSupplier(Long supplierId) {
		
		Supplier s = this.readSupplier(supplierId);
		
		if (s == null)
			return false;
		
		try {
			eM.remove(s);
		} catch (IllegalArgumentException e) {
			return false;
		} catch (Exception e2) {
			return null;
		}
		
		return true;
	}
	
	public HashMap<Long, Supplier>  getRegister()
	{
		return null;
	}
}
